package main

import (
	"gin/database"
	"gin/queue"
	"gin/router"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	etcd_common "github.com/teamones-open/etcd-discovery/common"
	logHook "github.com/teamones-open/logrus-log-hook"
	"net/http"
	"os"
)

func main() {
	InitConfig()
	SetGinMode()
	InitLogrus()
	queue.InitQueueWorkConfig()

	db := Mysql.InitDB()
	defer db.Close()
	router.InitRouter()
}

func InitConfig() {
	workDir, _ := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/config")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
}

func InitLogrus() {
	serviceName := viper.GetString("etcd.serverName")
	logServerUrl := viper.GetString("logServer.url")
	hook := logHook.New(
		serviceName,
		logServerUrl,
		logrus.AllLevels,
	)

	hook.BeforePost = func(req *http.Request) error {
		return nil
	}
	hook.AfterPost = func(res *http.Response) error {
		return nil
	}

	logrus.AddHook(hook)
}

func SetGinMode() {
	mode := viper.GetString("server.mode")
	if mode == "release" {
		gin.SetMode(gin.ReleaseMode)
		etcd_common.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
		etcd_common.SetMode(gin.DebugMode)
	}
}
